﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Luna.Extender;
using System.Windows.Forms;
using System.Reflection;
using Luna.Service;
using System.Drawing;

namespace Luna.Framework.Extender
{
	public enum MenuItemType
	{
		Button, Label, Separator, DropDown
	}

	public class MenuExtender: IFormExtension
	{
		private MenuStrip menu;

		public IAppContext Context { get; private set; }

		public virtual ToolStripItem createMenuItem(IExtensionItem item) {
			ToolStripItem result = null;
			MenuItemType type = (MenuItemType)Enum.Parse(typeof(MenuItemType),  
				item["type"].getDefaultValue("Button"));
			switch (type) {
				case MenuItemType.Button:
					ToolStripMenuItem mItem = new ToolStripMenuItem();
					// decorate the menu item
					string uriFigText = item["image"];
					if (uriFigText.isNotNullAndEmpty()) {
						Uri uriFig = new Uri(uriFigText);
						mItem.Image = uriFig.resolveObject<Image>();
					}

					// create child item
					foreach (IExtensionItem child in item.Children)
						if ("item".Equals(child.Name)) {
							ToolStripItem childItem = createMenuItem(child);
							mItem.DropDownItems.Add(childItem);
						}

					// create  handler for this item, if any
					bindMenuItem(Context, mItem, item);
					result = (ToolStripItem)mItem;
					break;
				case MenuItemType.Separator:
					result = new ToolStripSeparator();
					break;
				default:
					break;
			}
			if (result != null) {
				Context[result] = item;
				result.Name = item["name"].getDefaultValue("");
				result.Text = item["text"].getDefaultValue(result.Name);
			}
			return result;
		}

		public virtual void bindMenuItem(IAppContext context, ToolStripItem mItem, IExtensionItem eItem) {
			string handler = eItem["handler"];
			if (handler.isNotNullAndEmpty()) {
				string[] parts = handler.Split(new char[] {'.'}, 2);
				object obj = context[parts[0]];
				if (obj != null && parts.Length > 1) {
					MethodInfo med = obj.getMember<MethodInfo>(parts[1], false);
					if (med != null)
						mItem.Click += (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), obj, parts[1], true);
				}
				else if (obj is IAction) {
					throw new NotImplementedException();
				}
				else {
					IActionManager manager = context.getService<IActionManager>();
					if (manager != null)
						throw new NotImplementedException();
				}
			}
		}

		#region IFormExtension Members

		public virtual void extent(IAppContext context, Form form, IExtensionItem ep) {
			Context = form.getPropertyValue<IAppContext>("Context", null).getDefaultValue(Context);

			menu = new MenuStrip();
			menu.Parent = form;

			foreach (IExtensionItem item in ep.Children)
				if (item.Name.Equals("item")) {
					ToolStripItem menuItem = createMenuItem(item);
					if (menuItem != null) 
						menu.Items.Add(menuItem);
				}

		}

		#endregion
	}
}
